/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.Expression;

import java.util.Map;
import java.util.Stack;

/**
 *
 * @author WIN7
 */
//Xu Ly Toan Tu Logic
class Bool implements Expression<Boolean> {
    private Boolean    number;
    public Bool(Boolean number)       { this.number = number; }
    @Override
    public Boolean interpret(Map<String,Expression> variables)  { return number; }    
}
class And implements Expression<Boolean> {
    Expression leftOperand;
    Expression rightOperand;
    public And(Expression left, Expression right) { 
        leftOperand = left; 
        rightOperand = right;
    }
 
    @Override
    public Boolean  interpret(Map<String,Expression> variables)  { 
        return (Boolean)leftOperand.interpret(variables) & (Boolean)rightOperand.interpret(variables);
    }
}
class Or implements Expression<Boolean> {
    Expression leftOperand;
    Expression rightOperand;
    public Or(Expression left, Expression right) { 
        leftOperand = left; 
        rightOperand = right;
    }
 
    @Override
    public Boolean  interpret(Map<String,Expression> variables)  { 
        return (Boolean)leftOperand.interpret(variables) | (Boolean)rightOperand.interpret(variables);
    }
}
class VariableLogic implements Expression<Boolean> {
    private String name;
    public VariableLogic(String name)       { this.name = name; }
    @Override
    public Boolean interpret(Map<String,Expression> variables)  { 
        if(null==variables.get(name)) return Boolean.valueOf(true); //Either return new Number(0).
        return (Boolean) variables.get(name).interpret(variables); 
    }
}
class EvaluatorLogic implements Expression<Boolean> {
    private Expression syntaxTree;
 
    public EvaluatorLogic(String expression) {
        Stack<Expression> expressionStack = new Stack<Expression>();
        for (String token : expression.split(" ")) {
            if  (token.equals("&")) {
                Expression subExpression = new And(expressionStack.pop(), expressionStack.pop());
                expressionStack.push( subExpression );
            }
            else if (token.equals("|")) {
                // it's necessary remove first the right operand from the stack
                Expression right = expressionStack.pop();
                // ..and after the left one
                Expression left = expressionStack.pop();
                Expression subExpression = new Or(left, right);
                expressionStack.push( subExpression );
            }
            else                        
                expressionStack.push( new VariableLogic(token) );
        }
        syntaxTree = expressionStack.pop();
    }
 
    @Override
    public Boolean   interpret(Map<String,Expression> context) {
        return (Boolean) syntaxTree.interpret(context);
    }
}
